package com.zhangshitong.springbootModel.utils;


import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.module.SimpleModule;

public class JsonUtil {

	private static JsonUtil jsonUtil;
	  private ObjectMapper mapper;

	  public JsonUtil(ObjectMapper mapper)
	  {
	    this.mapper = mapper;
	  }

	  private static JsonUtil getInstance() {
	    if (jsonUtil == null) {
	      ObjectMapper mapper = new ObjectMapper();
	      SimpleModule module = new SimpleModule("JsonUtil", 
	        new Version(1, 0, 0, null));
	      module.addSerializer(new LongSerializer());
	      module.addSerializer(new TimestampSerializer());
	      mapper.registerModule(module);
	      jsonUtil = new JsonUtil(mapper);
	    }
	    return jsonUtil;
	  }

	  public ObjectMapper getMapper() {
	    return this.mapper;
	  }

	  public static <T> T jsonToObject(String json, Class<T> clazz) throws Exception {
	    return getInstance().getMapper().readValue(json, clazz);
	  }

	  public static String toJson(Object value) throws Exception {
	    return getInstance().getMapper().writeValueAsString(value);
	  }


}
